package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Transactional
    @Override
    public ResponseResult login(AdUserDTO adUserDTO) {
        // 1. 校验参数
        String name = adUserDTO.getName();
        String password = adUserDTO.getPassword();
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //2.查询用户的信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adUserDTO.getName()));
        //2.1用户名不能为空
        if (adUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码不能为空");
        }
        //3.获取密码和盐
        //3.1利用md5进行加盐处理
        String Pwd = DigestUtils.md5DigestAsHex((password + adUser.getSalt()).getBytes());
        //5.判断密码是否一致
        if (!Pwd.equals(adUser.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
        }
        //判断用户状态
        if (adUser.getStatus().intValue() != 9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户状态异常，无法登录");
        }
        //6.用户修改登录时间
        adUser.setLoginTime(new Date());
        this.updateById(adUser);

        //7.给用户颁发token jwt 令牌
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        //8.用户信息返回到实体类vo中
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(adUser,userVO);
        //9返回响应的结果
        Map map = new HashMap<>();
        //key是唯一的，token,user
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}
